//
//  SLCACustomDemoController.m
//  Objective-C
//
//  Created by 陆承东 on 2018/7/12.
//  Copyright © 2018年 S_Line. All rights reserved.
//

#import "SLCACustomDemoController.h"

#import "SLYJLodingView.h"

@interface SLCACustomDemoController ()

@property (nonatomic, weak) CADisplayLink *displayLink;
@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, assign) BOOL isAnimation;
@property (nonatomic, weak) SLYJLodingView *loadingView;

@end

@implementation SLCACustomDemoController

- (void)initNavBar {
    self.navTitle = @"CACustomDemo";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavBar];
    
    [self initView];
    
    [self startTimer];
}

- (void)initView {
    SLYJLodingView *loadingView = [[SLYJLodingView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight + 20, kScreenWidth, 88)];
    self.loadingView = loadingView;
    [self.view addSubview:loadingView];
}

- (void)startTimer {
    CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(calculateProgress)];
    self.displayLink = displayLink;
    [displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)calculateProgress {
    self.progress = self.progress + 1.0 / 100.0;
    if (self.progress > 3.0) {
        if (self.isAnimation) {
            [self.loadingView stopAnimation];
            self.isAnimation = false;
        }
        self.progress = 0.0;
    }
    if (self.progress > 2.0) {
        if (!self.isAnimation) {
            [self.loadingView startAnimation];
            self.isAnimation = true;
        }
    }
    
    self.loadingView.progress = self.progress < 1.0 ? 0.0 : self.progress - 1.0;
}

- (void)dealloc {
    [self.displayLink invalidate];
    self.displayLink = nil;
}

@end
